<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template v-if="meta.indexOf('EquipmentLeaseExport') > -1" #btns>
        <el-button type="primary" :loading="exportLoading" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tablec"
    >
      <el-table-column
        align="center"
        :label="$t('message.zldh')"
        prop="id"
        min-width="120"
        show-overflow-tooltip
      >
        <template v-if="meta.indexOf('EquipmentLeaseDetail') > -1" v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.id)">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="$t('message.zlqc')"
        prop="equipmentName"
        min-width="140"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.zlrxx')"
        prop="leaseUserInfo"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.zlrlx')"
        prop="leaseUserType"
        min-width="120"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span>{{ scope.row.leaseUserType == 1 ? $t('message.hy'):$t('message.sk'), }}</span>
        </template>
      </el-table-column>p
      <el-table-column
        align="center"
        :label="$t('message.zlsj')"
        prop="leaseTime"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.wdsj')"
        prop="backTime"
        show-overflow-tooltip
        min-width="160"
      />
      <el-table-column
        align="center"
        :label="$t('message.zffs')"
        prop="payMethodName"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="$t('message.bz')"
        prop="remark"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column :label="$t('message.zfzt')" prop="payStatus" min-width="100" align="center" fixed="right">
        <template slot-scope="scope">
          {{ scope.row.payStatus === "0" ? $t('message.dzf') : scope.row.payStatus === "1" ? $t('message.cswzf') : scope.row.payStatus === "2" ? $t('message.qxzf') : scope.row.payStatus === "3" ? $t('message.zfcg') : scope.row.payStatus === "4" ? $t('message.tkz') : scope.row.payStatus === "5" ? $t('message.tkcg') : "" }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.status')" prop="status" min-width="100" align="center" fixed="right">
        <template slot-scope="scope">
          {{ scope.row.status === "0" ? $t('message.zlz') :scope.row.status === "1" ? $t('message.ygh') : scope.row.status === "2" ? $t('message.dzf') :scope.row.status === "3" ? $t('message.qxzf'): "" }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.caozuo')"
        :width="$i18n.locale === 'ZH'? 160 : 320"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="scope.row.payStatus === '0' && meta.indexOf('EquipmentLeaseCancelPay') > -1"
              v-preventReClick
              type="text"
              @click="deleteOrder(scope.row)"
            >{{ $t('message.qxzf') }}</el-button>
            <el-button
              v-if="scope.row.payStatus === '0' && meta.indexOf('EquipmentLeaseContinuePay') > -1"
              v-preventReClick
              type="text"
              @click="jxzfBtn(scope.row)"
            >{{ $t('message.jxzf') }}</el-button>
            <el-button
              v-if="scope.row.status === '0' && scope.row.payStatus === '3' && meta.indexOf('EquipmentReturn') > -1"
              v-preventReClick
              type="text"
              @click="showGh(scope.row)"
            >{{ $t('message.guhuan') }}</el-button>
            <el-button
              v-if="scope.row.payStatus == 3 || scope.row.payStatus == 5"
              v-preventReClick
              type="text"
              @click="print(scope.row)"
            >{{ $t('message.dyxp') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog
      :title="$t('message.ghqc')"
      :visible.sync="showTc"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :append-to-body="true"
      width="800px"
    >
      <el-table
        ref="tables"
        :data="showGhMoney?multipleSelectionb:ghList"
        border
        fit
        :header-row-class-name="'table-header'"
        class="doumee-element-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="!showGhMoney"
          type="selection"
          align="center"
          width="55"
        />
        <el-table-column
          align="center"
          :label="$t('message.qcmc')"
          prop="equipmentName"
          show-overflow-tooltip
          min-width="120"
        />

        <el-table-column
          align="center"
          :label="$t('message.zfyj')"
          show-overflow-tooltip
          prop="deposit"
          min-width="80"
        />
        <el-table-column
          align="center"
          :label="$t('message.sfbz')"
          show-overflow-tooltip
          prop="chargeInfo"
          min-width="150"
        />
        <el-table-column
          :label="$t('message.zlsj')"
          prop="leaseTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          :label="$t('message.mfsjfz')"
          prop="freeTime"
          show-overflow-tooltip
          min-width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.freeTime || 0 }}
          </template></el-table-column>
      </el-table>

      <el-form v-if="showGhMoney" ref="ruleForm" :model="ruleForm" label-width="auto" label-suffix="：" style="margin-top: 20px;">
        <el-form-item :label="$t('message.styj')" prop="deposit">
          <el-input
            v-model="ruleForm.deposit"
            maxlength="50"
            oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1');"
            style="width: 100%;"
            :placeholder="$t('message.qsr') + $t('message.styj')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.bz')" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            maxlength="200"
            style="width: 100%;"
            :placeholder="$t('message.qsr') + $t('message.bz')"
          />
        </el-form-item>
      </el-form>
      <div v-if="!showGhMoney" slot="footer" class="dialog-footer">
        <el-button @click="showTc = false">{{ $t('message.qx') }}</el-button>
        <el-button type="primary" @click="qrGhbtn">{{ $t('message.guhuan') }}</el-button>
      </div>
      <div v-if="showGhMoney" slot="footer" class="dialog-footer">
        <el-button @click="showGhMoney = false">{{ $t('message.qx') }}</el-button>
        <el-button type="primary" :loading="subloading" @click="ghBtn">{{ $t('message.guhuan') }}</el-button>
      </div>
    </el-dialog>
    <OrderDetail ref="OrderDetail" />
    <RechargeTem v-if="isPrint" ref="RechargeTemRef" />
    <RefundTem v-if="isPrint" ref="RefundTemRef" />
    <orderDialog ref="child" @orderSuccess="getList" />
  </div>
</template>

<script>
import store from '@/store'
import { equipmentLeaseRecord, equipmentLeaseExport, equipmentReturn, equipmentReturnMoney, equipmentUnReturnDetail, equipmentLeaseCancelPay, printOrder } from '@/api'
import { parseTime } from '@/utils/index'
import Pagination from '@/components/paginations'
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './components/config'
import OrderDetail from './components/orderDetail.vue'
import orderDialog from '@/components/order'
import RechargeTem from '@/components/printTem/recharge.vue'
import RefundTem from '@/components/printTem/refund.vue'
export default {
  name: 'Lease',
  components: {
    QueryForm,
    Pagination,
    orderDialog,
    OrderDetail,
    RechargeTem,
    RefundTem
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      meta: [],
      queryFormConfig,
      list: [],
      isPrint: false,
      subloading: false,
      listLoading: true,
      exportLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      ghList: [],
      total: 0,
      filters: {},
      showTc: false,
      multipleSelection: [],
      multipleSelectionb: [],
      ruleForm: {},
      showGhMoney: false,
      ghRow: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
  },
  activated() {
    this.getList(1)
  },
  methods: {
    handleDetail(id) {
      this.$refs.OrderDetail.getOrderDetail(id)
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    deleteOrder(row) {
      // 取消该订单
      this.$confirm(this.$t('message.qxddtc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          equipmentLeaseCancelPay({
            param: {
              id: row.id
            }
          })
            .then((res) => {
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.qxcg'))
                this.getList()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        })
        .catch(() => {})
    },
    jxzfBtn(row) {
      this.$refs.child.continuePay(row, 'leaseList')
    },
    exportExcel() {
      this.exportLoading = true
      const { filters } = this
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = ''
        filters.endTime = ''
      }
      equipmentLeaseExport({
        param: { ...filters }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            window.open(res.record.showUrl, '_blank')
          }
        })
        .catch(() => { this.exportLoading = false })
    },
    print(row) {
      this.$confirm(this.$t('message.dyxptc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          this.isPrint = true
          printOrder({
            param: {
              contentMap: {},
              venueId: sessionStorage.getItem('venueId'),
              workId: row.orderId,
              templateCode: row.status === '0' ? 'LEAST_TMPL' : 'LEAST_RETURN_TMPL'
            }
          })
            .then((res) => {
              if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
                res.record.dataList.forEach(item => {
                  this.$refs.RechargeTemRef.obj = { ...item, ddstatus: row.status }
                  this.$refs.RechargeTemRef.desc = this.$t('message.ZLTemPlace')
                  setTimeout(() => {
                    this.$refs.RechargeTemRef.print()
                  }, 300)
                  setTimeout(() => {
                    this.isPrint = false
                  }, 500)
                })
              } else {
                this.$message.success(this.$t('message.dycg'))
                this.isPrint = false
              }
            })
            .catch((err) => {
              this.isPrint = false
              console.log(err)
            })
        })
        .catch(() => { })
    },
    printRe(row) {
      this.$confirm(this.$t('message.dyxptc'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx'),
        type: 'warning'
      })
        .then(() => {
          this.isPrint = true
          printOrder({
            param: {
              contentMap: {},
              venueId: sessionStorage.getItem('venueId'),
              workId: row.orderId,
              templateCode: row.status === '0' ? 'LEAST_TMPL' : 'LEAST_RETURN_TMPL'
            }
          })
            .then((res) => {
              if (res.record && res.record.isPrint === '1' && res.record.dataList && res.record.dataList.length > 0) {
                res.record.dataList.forEach(item => {
                  // this.$refs.RefundTemRef.obj = { ...item, ddstatus: row.status }
                  // setTimeout(() => {
                  //   this.$refs.RefundTemRef.print()
                  // })
                  this.$refs.RechargeTemRef.obj = { ...item, ddstatus: row.status }
                  this.$refs.RechargeTemRef.desc = this.$t('message.ZLTemPlace')
                  setTimeout(() => {
                    this.$refs.RechargeTemRef.print()
                  })
                  setTimeout(() => {
                    this.isPrint = false
                  }, 500)
                }, 300)
              } else {
                this.isPrint = false
                this.$message.success(this.$t('message.dycg'))
              }
            })
            .catch((err) => {
              this.isPrint = false
              console.log(err)
            })
        })
        .catch(() => { })
    },
    showGh(row) {
      this.ghRow = row
      equipmentUnReturnDetail({ param: { id: row.id }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.showTc = true
          this.showGhMoney = false
          this.multipleSelection = []
          this.ghList = res.recordList
          this.$nextTick(() => {
            this.$refs.tables.doLayout()
          })
        })
        .catch(() => {})
    },
    qrGhbtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        let recordDetailIds = []
        const multipleSelection = [...this.multipleSelection]
        recordDetailIds = multipleSelection.map((s) => s.recordDetailId)
        const recordId = multipleSelection[0].recordId
        let deposit = 0
        multipleSelection.forEach((s) => {
          deposit = deposit + Number(s.deposit)
        })
        equipmentReturnMoney({ param: { recordDetailIds, recordId }})
          .then((res) => {
            if (res.errorCode !== '000000') return
            this.ruleForm = { recordDetailIds, recordId, deposit: res.record.backDeposit, backDeposit: res.record.backDeposit }
            this.showGhMoney = true
            this.multipleSelectionb = multipleSelection
            this.$nextTick(() => {
              this.$refs.tables.doLayout()
            })
          })
          .catch(() => { })
      } else {
        this.$message.info(this.$t('message.qxz') + this.$t('message.ghqc'))
      }
    },
    ghBtn() {
      const param = { ...this.ruleForm }
      if (!param.deposit && param.deposit !== '0' && param.deposit !== 0) {
        this.$message.info(this.$t('message.qsr') + this.$t('message.styj'))
        return false
      }
      if (Number(param.deposit) === Number(param.backDeposit)) {
        param.isChange = '0'
      } else {
        param.isChange = '1'
      }
      param.deposit = Number(param.deposit)
      this.subloading = true
      equipmentReturn({ param })
        .then((res) => {
          this.subloading = false
          if (res.errorCode !== '000000') return
          this.$message.success(this.$t('message.ghcg'))
          this.showTc = false
          this.showGhMoney = false
          const row = {
            ...this.ghRow,
            status: '1'
          }
          this.printRe(row)
          this.getList()
        })
        .catch(() => { this.subloading = false })
    },
    // 获取列表
    getList(page) {
      const { pagination, filters } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        this.pagination.page = page
        pagination.page = page
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.time && filters.time.length > 0) {
        filters.startTime = filters.time[0]
        filters.endTime = filters.time[1]
      } else {
        filters.startTime = ''
        filters.endTime = ''
      }
      this.listLoading = true
      equipmentLeaseRecord({ pagination, param: { venueId, ...filters }})
        .then((res) => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.total = res.totalCount
          if (res.totalCount && res.recordList.length === 0 && pagination.page > 1) {
            this.getList(Math.ceil(res.totalCount / pagination.rows))
          }
          this.$refs.table.doLayout()
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 清空
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>

